App.DocumentStore = new Opal.Store({
    fields: ["id","name","description","category","image","created_at","updated_at"],
    url: App.contextPath + "/documents",
    paginate: true
});

App.DocumentView = new Opal.View({
    templateName: "#documents-template",
    rootElement: "#section-container"
});

App.DocumentPaginationView = new Opal.View({
    templateName: "#pagination",
    rootElement: ".documents-pagination"
});

DocumentController = Opal.Controller.extend({        
    currentPage:1,
    categoryId:null,
    
    init: function (params) {
        this._super();
        this.categoryId = params.category;
        this.reload(params);
    },
    paginate: function(page,category_id) {                
        this.categoryId = category_id;
        
        App.DocumentController.reload({
            page: page,
            category: category_id
        });
    },
    search: function(params) {
        App.DocumentController.reload(params);
    },
    deleteDocument: function(document_id) {
       var proxy = new Opal.Proxy(App.contextPath + "/documents/delete/"+document_id);
       proxy.sendData({           
       },function() {
           App.DocumentController.reload({
               page: 1,
               category: App.DocumentController.categoryId
           });
       });
    },
    reload: function(params,callback) {        
        App.DocumentView.showLoader();
        App.DocumentStore.load(params,function(data) {
           App.DocumentView.hideLoader();
           App.DocumentView.context = { 
               category_id: data.category_id,
               category_code: data.category_code,
               category_name: data.category_name,
               documents: data.entries 
           };
           App.DocumentView.show("clean-append");
           
           App.DocumentPaginationView.context = {
               currentPage: data.currentPage,
               perPage: data.perPage,
               totalEntries: data.totalEntries,
               category_id: data.category_id,
               paginateFunction: "paginate"
           };
           App.DocumentPaginationView.show("clean-append");
           
           if (callback != undefined) {
               callback();
           }
        });
    }
});

function paginate(page,category_id) {
    App.DocumentController.paginate(page,category_id);
}